<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="88px">
          <el-form-item label="健身房名称" prop="gymName">
            <el-input v-model="queryParams.gymName" placeholder="请输入健身房名称" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['primary:gym:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['primary:gym:edit']">修改</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['primary:gym:export']">导出</el-button>
          </el-col>

          <!--        <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handledate()">设置私教预约时间</el-button>
          </el-col> -->

          <!--        <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleaddguize"
              v-hasPermi="['primary:gym:add']">添加规则</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="gymList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!--        <el-table-column label="健身房id" align="center" prop="id" v-if="true" />
        <el-table-column label="部门id" align="center" prop="deptId" /> -->
        <!-- <el-table-column label="健身房管理员账号id" align="center" prop="userId" /> -->
        <!-- <el-table-column label="健身房编号" align="center" prop="gymNo" /> -->
        <el-table-column label="健身房名称" align="center" prop="gymName" />
        <!-- <el-table-column label="排序值" align="center" prop="sort" /> -->
        <el-table-column label="健身房描述信息" align="center" prop="gymInfo" />
        <el-table-column label="健身房所在城市" align="center" prop="city" />
        <el-table-column label="健身房地址" align="center" prop="address" />
        <el-table-column label="健身房联系电话" align="center" prop="phone" />
        <!-- <el-table-column label="健身房营业状态；0-营业中；1-已关门；2-筹建中；3-暂停营业" align="center" prop="status" /> -->
        <el-table-column label="营业状态" align="center">
          <template #default="scope">
            <dict-tag :options="g_gyms_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="经度" align="center" prop="longitude" />
        <el-table-column label="纬度" align="center" prop="latitude" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:gym:edit']"></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['primary:gym:remove']"></el-button>
            </el-tooltip> -->
            <el-tooltip content="场馆二维码" placement="top">
              <el-button link type="primary" icon="MessageBox" @click="handleUpdateB(scope.row)"
                v-hasPermi="['primary:gym:edit']"></el-button>
            </el-tooltip>
            
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:gym:edit']"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改健身房规则 -->
    <!--    <el-dialog :title="guize.title" v-model="guize.visible" width="560px" append-to-body>
      <el-form ref="gymFormRef" :model="guizeInfo" label-width="150px">

        <el-form-item label="限制数量">
          <el-input v-model="guizeInfo.restrictNumber" placeholder="请输入限制数量" type="number" :min="1"/>
        </el-form-item>
        <el-form-item label="私教预约人数上限" prop="longitude">
          <el-input v-model="guizeInfo.privateTeachingPeopleMax" placeholder="请输入私教预约人数上限" type="number" :min="1"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormb">确 定</el-button>
          <el-button @click="cancelb">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
    <!-- 添加或修改健身房信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="560px" append-to-body>
      <el-form ref="gymFormRef" :model="form" :rules="rules" label-width="120px">
        <!--      <el-form-item label="部门id" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门id" />
        </el-form-item> -->
        <!--     <el-form-item label="健身房管理员账号id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入健身房管理员账号id" />
        </el-form-item> -->
        <!--    <el-form-item label="健身房编号" prop="gymNo">
          <el-input v-model="form.gymNo" placeholder="请输入健身房编号" />
        </el-form-item> -->
        <el-form-item label="图片" prop="ossId">
          <imageUpload v-model="form.ossId" ref="childValue" :limit='5' />
        </el-form-item>
        <el-form-item label="健身房名称" prop="gymName">
          <el-input v-model="form.gymName" placeholder="请输入健身房名称" @input="trimInput('gymName')" />
        </el-form-item>
        <el-form-item label="营业状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option v-for="dict in g_gyms_status" :key="dict.value" :label="dict.label"
              :value="Number(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!--   <el-form-item label="排序值" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序值" />
        </el-form-item> -->
        <el-form-item label="健身房描述信息" prop="gymInfo">
          <el-input v-model="form.gymInfo" type="textarea" placeholder="请输入内容" @input="trimInput('gymInfo')" />
        </el-form-item>
        <el-form-item label="健身房所在城市" prop="city">
          <el-input v-model="form.city" placeholder="请输入健身房所在城市" @input="trimInput('city')" />
        </el-form-item>
        <el-form-item label="健身房地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入内容" @input="trimInput('address')" />
        </el-form-item>
        <el-form-item label="健身房联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入健身房联系电话" @input="trimInput('phone')" />
        </el-form-item>
        <!--       <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="dialogb.title" v-model="dialogb.visible" width="580px" append-to-body>
      <el-form ref="privateTeachingScheduleFormRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="私教开始时间" prop="StartTime">
          <el-time-select v-model="form.StartTime" style="width: 215px" class="mr-4" placeholder="开始时间" start="00:00"
            step="00:10" end="23:59" />
        </el-form-item>

        <el-form-item label="私教结束时间" prop="EndTime">
          <el-time-select v-model="form.EndTime" style="width: 215px" class="mr-4" placeholder="结束时间" start="00:00"
            step="00:10" end="23:59" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormb">确 定</el-button>
          <el-button @click="cancelc">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="dialogc.title" v-model="dialogc.visible" width="560px" append-to-body>
      <div class='table-main'>
        <div id="your-div-id" v-for="(text, index) in array" :key="index" class="qr-container">
          <div :id="'qryour-' + index" class="qr-item" style="width: 100%;">
            <div class="qr-code">
              <div :id="'qrcode-' + index"></div>
            </div>
            <div class="device-info">
              <div class="device-text">
                <text>{{ form.gymName }}</text>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="downloadImage">保存到本地</el-button>
          <el-button @click="cancelQrcode">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Gym" lang="ts">
  import { listGym, getGym, delGym, addGym, updateGym, addguize } from '@/api/primary/gym';
  import { updatetime } from '@/api/primary/privateTeachingSchedule';
  import { GymVO, GymQuery, GymForm } from '@/api/primary/gym/types';
  import { nextTick } from 'vue';
  import QRcode from 'qrcodejs2-fix';
  import html2canvas from 'html2canvas';
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { g_gyms_status } = toRefs<any>(proxy?.useDict('g_gyms_status'));

  const gymList = ref<GymVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const imageUploadRef = ref(null);
  const queryFormRef = ref<ElFormInstance>();
  const gymFormRef = ref<ElFormInstance>();
  const dialogb = reactive<DialogOption>({
    visible: false,
    title: '',
  });
  const guize = reactive<any>({
    visible: false,
    title: ''
  });
  const guizeInfo = reactive<any>({
    restrictNumber: 0,
    privateTeachingPeopleMax: 0
  });
  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  const dialogc = reactive<DialogOption>({
    visible: false,
    title: ''
  });


  const initFormData : GymForm = {
    id: undefined,
    deptId: undefined,
    userId: undefined,
    gymNo: undefined,
    gymName: undefined,
    sort: undefined,
    gymInfo: undefined,
    city: undefined,
    address: undefined,
    phone: undefined,
    status: undefined,
    longitude: undefined,
    latitude: undefined,
    ossId: undefined,
    StartTime: undefined,
    EndTime: undefined,
    businessHours: undefined
  }
  const data = reactive<PageData<GymForm, GymQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      StartTime: undefined,
      EndTime: undefined,
      businessHours: undefined,
      ossId: undefined,
      deptId: undefined,
      userId: undefined,
      gymNo: undefined,
      gymName: undefined,
      sort: undefined,
      gymInfo: undefined,
      city: undefined,
      address: undefined,
      phone: undefined,
      status: undefined,
      longitude: undefined,
      latitude: undefined,
      params: {
      }
    },
    rules: {
      ossId: [
        { required: true, message: "图片不能为空", trigger: "blur" }
      ],
      id: [
        { required: true, message: "健身房id不能为空", trigger: "blur" }
      ],
      deptId: [
        { required: true, message: "部门id不能为空", trigger: "blur" }
      ],
      userId: [
        { required: true, message: "健身房管理员账号id不能为空", trigger: "blur" }
      ],
      gymNo: [
        { required: true, message: "健身房编号不能为空", trigger: "blur" }
      ],
      gymName: [
        { required: true, message: "健身房名称不能为空", trigger: "blur" }
      ],
      sort: [
        { required: true, message: "排序值不能为空", trigger: "blur" }
      ],
      gymInfo: [
        { required: true, message: "健身房描述信息不能为空", trigger: "blur" }
      ],
      city: [
        { required: true, message: "健身房所在城市不能为空", trigger: "blur" }
      ],
      address: [
        { required: true, message: "健身房地址不能为空", trigger: "blur" }
      ],
      phone: [
        { required: true, message: "健身房联系电话不能为空", trigger: "blur" }
      ],
      status: [
        { required: true, message: "健身房营业状态；0-营业中；1-已关门；2-筹建中；3-暂停营业不能为空", trigger: "change" }
      ],
      longitude: [
        { required: true, message: "经度不能为空", trigger: "blur" }
      ],
      latitude: [
        { required: true, message: "纬度不能为空", trigger: "blur" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询健身房信息列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listGym(queryParams.value);
    gymList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }
  const trimInput = (field) => {
    nextTick(() => {
      if (form.value[field]) {
        form.value[field] = form.value[field].trim();
      }
    });
  };
  // const getListguize = async () => {
  //   loading.value = true;
  //   const res = await listguize(queryParams.value);
  //   gymList.value = res.rows;
  //   total.value = res.total;
  //   loading.value = false;
  // }
  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }
  const cancelb = () => {
    guize.visible = false;
  }

  const cancelQrcode = () => {
    dialogc.visible = false;
  }
  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    gymFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : GymVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加健身房信息";
  }
  const handleaddguize = () => {
    reset();
    guize.visible = true;
    guize.title = "添加健身房规则";
  }
  /** 修改按钮操作 */
  const handleUpdate = async (row ?: GymVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getGym(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改健身房信息";
  }
  const handleUpdateB = async (row ?: GymVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getGym(_id);
    Object.assign(form.value, res.data);
    dialogc.visible = true;
    dialogc.title = "健身房二维码";
    createQrCode()
  }

  const array = ref([]);
  const createQrCode = async () => {
    const formId = form.value.id;  // 获取 form.value.id 的值
    const list = [`https://gym.cytingchechang.com?ida=${formId}`]; // 动态构建 URL
    array.value = list
    nextTick(() => {
      list.forEach((text, index) => {
        const qrElementId = `qrcode-${index}`;
        let oldQrCode = document.getElementById(qrElementId);

        if (oldQrCode) {
          oldQrCode.innerHTML = ''; // 清空二维码容器的内部HTML
        }

        new QRcode(qrElementId, {
          text: text,
          width: 250,
          height: 250
        });
      });

    });
  }

  const downloadImage = async () => {
    const elementId = 'your-div-id'; // 指定要截取的元素 ID
    const element = document.getElementById(elementId);

    if (!element) {
      console.error(`找不到 ${elementId} 该元素.`);
      return;
    }

    try {
      const canvas = await html2canvas(element);
      const base64Image = canvas.toDataURL('image/png');

      // 创建下载链接并下载图片
      const a = document.createElement('a');
      a.href = base64Image;
      a.download = '场馆二维码.png'; // 设置下载文件名
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a); // 下载完成后移除链接
    } catch (error) {
      console.error('无法下载:', error);
    }
  };

  /** 私教预约时间按钮操作 */
  const handledate = async (row) => {
    reset();
    const res = await getGym(row.id);
    if (res.data.businessHours) {
      form.value.StartTime = res.data.startTime
      form.value.EndTime = res.data.endTime
      form.value.id = row.id
    }

    dialogb.visible = true;
    dialogb.title = "场馆营业时间";
  }

  const cancelc = () => {
    reset();
    dialogb.visible = false;
  }
  // /** 提交按钮 */

  // const submitFormb = async () => {
  //   buttonLoading.value = true;
  //   const res = await addguize(guizeInfo);
  //   proxy?.$modal.msgSuccess("添加成功");
  //   guize.visible = false;
  //   buttonLoading.value = false;
  //   await getList();
  // }
  const submitFormb = async () => {
    let info = {
      businessHours: form.value.StartTime + ", " + form.value.EndTime,
      id: form.value.id
    }
    form.businessHours = form.value.StartTime + ", " + form.value.EndTime;
    form.value.StartTime = undefined
    form.value.EndTime = undefined
    form.value.id = undefined
    buttonLoading.value = true;
    await updatetime(info).finally(() => buttonLoading.value = false);
    proxy?.$modal.msgSuccess("修改成功");
    dialogb.visible = false;

  }

  /** 提交按钮 */
  const submitForm = () => {
    gymFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateGym(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          await addGym(form.value).finally(() => buttonLoading.value = false);
          queryParams.value.gymName = ''
          proxy?.$modal.msgSuccess("添加成功");
        }

        dialog.visible = false;
        await getList();
      }
    });
  }


  /** 删除按钮操作 */
  const handleDelete = async (row ?: GymVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除健身房信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delGym(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('primary/gym/export', {
      ...queryParams.value
    }, `gym_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    getList();
  });
</script>
<style lang="scss" scoped>
  .table-main {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 24px;
  }

  .qr-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    margin-bottom: 20px;
    margin-top: 24px;
    width: 360px;
    height: 360px;
    /* 可根据需要调整间距 */
  }

  .qr-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
  }

  .qr-code {
    margin-bottom: 20px;
    /* 可以调整间距 */
  }

  .device-info {
    display: flex;
    justify-content: center;
  }

  .device-text {
    font-size: 24px;
    font-weight: 600;
  }
</style>
